import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Row, Col, Card, Typography, Button, Statistic } from 'antd';
import { RadarChart, Radar, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Tooltip } from 'recharts';
import './index.css'; // 引入全局样式表
import axios from 'axios';
import { LeftOutlined } from '@ant-design/icons';
import moreSVG from '../../../assets/speech/exercise.svg';
import nextSVG from '../../../assets/speech/next.svg';
import PropTypes from 'prop-types'; 

const { Title } = Typography;

// 公共的 API 请求函数
const fetchData = async (url, params = {}) => {
  try {
    const response = await axios.get(url, { params });
    if (response.data && response.data.code === 200) {
      return response.data.data;
    } else {
      throw new Error(response.data.message || 'Request failed');
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
};

const StatisticBox = ({ title, value, color }) => {
  return (
    <div style={{ textAlign: 'center' }}>
      <Statistic value={value} valueStyle={{ color }} />
      <p>{title}</p>
    </div>
  );
};

// 定义 propTypes 来验证 props 的类型
StatisticBox.propTypes = {
  title: PropTypes.string.isRequired, // 标题应该是一个必需的字符串
  value: PropTypes.number.isRequired, // 值应该是一个必需的数字
  color: PropTypes.string,            // 颜色应该是字符串，默认非必需
};

const ReportOverallPerformance = ({ totalAnswers, goodPerformance, poorPerformance }) => {
  return (
    <div className="report-overall-performance">
      <Card 
        className="report-card" 
        title={
          <span 
            style={{ 
              color: '#23153C', 
              padding: '0 0px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '80px', // 设置宽度
              height: '40px',  // 设置高度
              borderRadius: '12px'
            }}
          >
            整体表现
          </span>
        } 
        bordered={false} 
        style={{ width: '100%' }}
      >
        <Row gutter={[48, 16]}>
          <Col span={8}>
            <StatisticBox title="回答总数" value={totalAnswers} />
          </Col>
          <Col span={8}>
            <StatisticBox title="表现不错" value={goodPerformance} color="#238CBA" />
          </Col>
          <Col span={8}>
            <StatisticBox title="表现不佳" value={poorPerformance} color="#f4377c" />
          </Col>
        </Row>
      </Card>
    </div>
  );
};

// 定义 propTypes 来验证 props 的类型
ReportOverallPerformance.propTypes = {
  totalAnswers: PropTypes.number.isRequired,   // 回答总数应该是一个必需的数字
  goodPerformance: PropTypes.number.isRequired, // 表现不错的数量应该是一个必需的数字
  poorPerformance: PropTypes.number.isRequired, // 表现不佳的数量应该是一个必需的数字
};

const ReportHeader = () => {
  const [chapterTitle, setChapterTitle] = useState('');
  const hashPath = window.location.hash;
  const pathParts = hashPath.split('/');
  const chapterID = pathParts[4];

  useEffect(() => {
    const fetchChapterTitle = async () => {
      try {
        const response = await fetchData(`http://localhost:8080/api/chapters/${chapterID}`);
        setChapterTitle(response.etitle);
      } catch (error) {
        console.error('Error fetching chapter title:', error);
      }
    };

    if (chapterID) {
      fetchChapterTitle();
    }
  }, [chapterID]);

  return (
    <div className="report-header">
      <Title level={2}>{chapterTitle} 练习结果报告</Title>
    </div>
  );
};

const ReportChart = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const hashPath = window.location.hash;
  const pathParts = hashPath.split('/');
  const chapterID = pathParts[4];
  // 从 Local Storage 中读取 userInfo
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString).userId : null;

  const fetchData = async (url, params) => {
    try {
      const response = await axios.get(url, { params: { userId: params.userId, chapterId: params.chapterId } });
      return response.data;
    } catch (error) {
      console.error('Error fetching data:', error);
      throw error; // 或者返回一个默认值
    }
  };

  const fetchUserRecordings = async () => {
    if (!userId || !chapterID) {
      setError('用户ID或章节ID无效');
      setLoading(false);
      return;
    }

    try {
      const response = await fetchData('/api/speech/user-chapter', {
        userId,
        chapterId: chapterID,
      });

      // 确保响应中有 data 字段
      if (response && response.data) {
        const userRecordings = response.data;

        // 计算平均分
        const totalPitchScore = userRecordings.reduce((acc, recording) => acc + recording.pitchScore, 0);
        const totalIntensityScore = userRecordings.reduce((acc, recording) => acc + recording.intensityScore, 0);
        const totalTextMatchScore = userRecordings.reduce((acc, recording) => acc + recording.textMatchScore, 0);
        const totalSpeechRateScore = userRecordings.reduce((acc, recording) => acc + recording.speechRateScore, 0);

        const count = userRecordings.length;
        const averagePitchScore = count > 0 ? totalPitchScore / count : 0;
        const averageIntensityScore = count > 0 ? totalIntensityScore / count : 0;
        const averageTextMatchScore = count > 0 ? totalTextMatchScore / count : 0;
        const averageSpeechRateScore = count > 0 ? totalSpeechRateScore / count : 0;

        const averageData = [
          { subject: 'Pitch', A: averagePitchScore, fullMark: 100 },
          { subject: 'Intensity', A: averageIntensityScore, fullMark: 100 },
          { subject: 'TextMatch', A: averageTextMatchScore, fullMark: 100 },
          { subject: 'SpeechRate', A: averageSpeechRateScore, fullMark: 100 },
        ];

        console.log('Average Data:', averageData); // 添加这行以查看输出的数据
        setData(averageData);
        setLoading(false);
      } else {
        setError('响应数据格式不正确');
        setLoading(false);
      }
    } catch (error) {
      console.error('获取用户录音记录时发生错误:', error);
      setError('暂无录音记录，先练习再来吧！');
      setLoading(false);
    }
  };

  useEffect(() => {
    if (userId && chapterID) {
      fetchUserRecordings();
    }
  }, [userId, chapterID]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '40vh' }}>
        <div style={{ textAlign: 'center' }}>{error}</div>
      </div>
    );
  }

  return (
    <div className="report-chart">
      <RadarChart cx={300} cy={250} outerRadius={150} width={600} height={500} data={data}>
        <PolarGrid />
        <PolarAngleAxis
          dataKey="subject"
          tick={{
            fontSize: 14, // 文字大小
            dy: 3, // 垂直偏移量，增加这个值可以使文字远离图表
          }}
          tickLine={{ stroke: '#ccc', strokeWidth: 1, strokeDasharray: '3 3' }} // 自定义刻度线样式
        />
        <PolarRadiusAxis domain={[0, 100]} />
        <Radar name="A" dataKey="A" stroke="#238CBA" fill="#23153C" fillOpacity={0.6} />
        <Tooltip />
      </RadarChart>
    </div>
  );
};

const ReportWeaknessAnalysis = ({ weaknesses }) => {
  return (
    <div className="report-card" style={{ width: '100%' }}>
      <div className="report-card-header">薄弱点分析</div>
      {weaknesses.map((item, index) => (
        <div key={index} className="report-weakness-card">
          <div className="report-weakness-card-title">
            <Title style={{ color: "#0D3245", marginLeft: 30 }} level={4}>{item.englishText}</Title>
          </div>
          <div className="report-weakness-card-description">
            {item.feedback.map((feedbackItem, feedbackIndex) => (
              <p key={feedbackIndex}>{feedbackItem}</p>
            ))}
          </div>
          <div className="report-weakness-card-score">
            <p>得分: {item.score}</p>
          </div>
        </div>
      ))}
    </div>
  );
};

// 定义 propTypes 来验证 props 的类型
ReportWeaknessAnalysis.propTypes = {
  weaknesses: PropTypes.arrayOf(
    PropTypes.shape({
      englishText: PropTypes.string.isRequired,
      feedback: PropTypes.arrayOf(PropTypes.string).isRequired,
      score: PropTypes.number.isRequired,
    })
  ).isRequired,
};

const SpeechReport = () => {
  const [weaknesses, setWeaknesses] = useState([]);
  const [totalAnswers, setTotalAnswers] = useState(0);
  const [goodPerformance, setGoodPerformance] = useState(0);
  const [poorPerformance, setPoorPerformance] = useState(0);

  // 从 Local Storage 中读取 userInfo
  const userInfoString = localStorage.getItem('userInfo');
  const userId = userInfoString ? JSON.parse(userInfoString).userId : null;

  // 获取章节ID
  const hashPath = window.location.hash;
  const pathParts = hashPath.split('/');
  const chapterId = pathParts[4];

  const fetchUserRecordings = async (setRecordings) => {
    try {
      const response = await fetchData(`/api/speech/user-chapter?userId=${userId}&chapterId=${chapterId}`);
      const recordings = response; // 直接使用响应数据，因为后端返回的就是列表
      const total = recordings.length;
      const good = recordings.filter(recording => recording.score >= 60).length;
      const poor = recordings.filter(recording => recording.score < 60).length;

      setTotalAnswers(total);
      setGoodPerformance(good);
      setPoorPerformance(poor);
      setRecordings(recordings); // 传递给外部函数
    } catch (error) {
      console.error('Error fetching user recordings:', error);
    }
  };

  const fetchWeaknesses = async (recordings) => {
    try {
      const feedbackData = recordings.map(item => ({
        feedback: item.recognitionResult.split('\n').map(line => line.trim()),
        score: item.score,
        sentenceId: item.sentenceId
      }));

      const sentenceIds = feedbackData.map(item => item.sentenceId);
      const sentences = await Promise.all(sentenceIds.map(id => fetchData(`/api/sentences/${id}`)));

      const weaknessesWithText = feedbackData.map((item, index) => ({
        ...item,
        englishText: sentences[index].englishText
      }));

      setWeaknesses(weaknessesWithText);
    } catch (error) {
      console.error('Error fetching weaknesses:', error);
    }
  };

  useEffect(() => {
    if (userId && chapterId) {
      fetchUserRecordings(async (recordings) => {
        await fetchWeaknesses(recordings);
      });
    }
  }, [userId, chapterId]);

  const navigate = useNavigate();
  const bookIdOrTitle = pathParts[2];

  const handleGoBack = (event) => {
    event.preventDefault(); // 阻止默认的链接行为
    window.history.back(); // 返回上一页
};

  const handleNextChapter = () => {
    const nextChapterId = parseInt(chapterId) + 1;
    navigate(`/dialogue/${bookIdOrTitle}/chapter/${nextChapterId}/sentence`, { replace: true });
    window.location.reload();
  };

  const ReportButtons = () => (
    <div className="report-buttons">
      <Button
        onClick={handleGoBack}
        style={{ marginRight: 50, width: 170, height: 50, backgroundColor: 'white', color: '#23153C', fontSize: 20 }}
      >
        <img src={moreSVG} alt="Restart" style={{ marginRight: 8, verticalAlign: 'middle' }} />
        重新练习
      </Button>
      <Button
        onClick={handleNextChapter}
        style={{ marginLeft: 50, width: 170, height: 50, backgroundColor: 'white', color: '#23153C', fontSize: 20 }}
      >
        <img src={nextSVG} alt="Next Chapter" style={{ marginRight: 8, verticalAlign: 'middle' }} />
        学习下一节
      </Button>
    </div>
  );

  return (
    <div>
      <Button icon={<LeftOutlined />} type="primary" onClick={handleGoBack} style={{ display: 'flex', alignItems: 'center',color:'#23153C',background:'white' ,marginLeft:30,marginTop:30}}>
        <span style={{ marginLeft: 3 }}>返回</span>
      </Button>
    <div className="report-container">
      
      <ReportHeader />
      <ReportChart />
      <div className="report-sections">
        <ReportOverallPerformance totalAnswers={totalAnswers} goodPerformance={goodPerformance} poorPerformance={poorPerformance} />
        <ReportWeaknessAnalysis weaknesses={weaknesses} />
      </div>
      <ReportButtons />
    </div>
    </div>
  );
};

export default SpeechReport;